package chapter14;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/22 16:47
 */
public class MemoryMapTest {
    public static void main(String[] args) {
        String file = "D:\\system_path备份20180507.txt";
        readFile(file);
    }

    private static void readFile(String fileName) {
        try (RandomAccessFile file = new RandomAccessFile(fileName, "rw"); ByteArrayOutputStream collector = new ByteArrayOutputStream()) {
            MappedByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, file.length());

            long count = file.length();
            byte[] dst = new byte[1024];
            while (count > 0) {
                int avalibleSize = count < 1024 ? (int) count : 1024;
                buffer.get(dst, 0, avalibleSize);
                collector.write(dst, 0, avalibleSize);
                count -= 1024;
            }

            String str = new String(collector.toByteArray());
            System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
